package com.financing.platform.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.dto.*;
import com.financing.platform.service.IFpOrderCostService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.financing.platform.activities.ActivitiesBusiness;
import com.financing.platform.activities.ActivitiesBusinessObject;
import com.financing.platform.common.BizEnums;
import com.financing.platform.dao.IFaUserDao;
import com.financing.platform.dao.IMessageDao;
import com.financing.platform.dao.IMessageNoteDao;
import com.financing.platform.dao.IMessageSmsDao;
import com.financing.platform.dao.IOrderDao;
import com.financing.platform.dao.IProjectDao;
import com.financing.platform.dao.IUserAccountDao;
import com.financing.platform.dao.IYouDanAmountDao;
import com.financing.platform.service.IActivitesService;
import com.financing.platform.service.IOrderService;
import com.financing.platform.service.IPaymentService;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MessageUtil;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.OrderManagerUserVO;
import com.financing.platform.vo.OrderVO;

/**
 * 
* @ClassName: OrderServiceImpl 
* @Description: 订单流程处理 
* @author chenming 
* @date 2014年8月18日 下午2:42:30 
****************************************
* admin-api-1.6 新增（20150318） 
*  后台操作 （已返佣- 反佣已确认） （合同已寄出 - 已打款）
*  lisu
****************************************  
*****************************************
* admin-api-1.13  
*  确认返佣（理财师已经收到返佣的钱）
*  lisu
****************************************  
*/
@Service("orderServiceImpl")
@Transactional
public class OrderServiceImpl extends BaseServiceImpl implements IOrderService {

	@Autowired
	private IOrderDao orderDaoImpl;
	
	@Autowired
	private IProjectDao projectDaoImpl;
	
	@Autowired
	private IFaUserDao faUserDaoImpl;
	
	@Autowired
	private IMessageDao messageDaoImpl;
	
	@Autowired
	private IMessageNoteDao messageNoteDaoImpl;
	
	@Autowired
	private IMessageSmsDao messageSmsDaoImpl;
	
	@Autowired
	private IUserAccountDao userAccountDaoImpl;
	
	@Autowired
	private IActivitesService activitesServiceImpl;
	
	@Autowired
	private IYouDanAmountDao youDanAmountDaoImpl;
	
	@Autowired
	private IPaymentService paymentServiceImpl;

	@Autowired
	private IFpOrderCostService fpOrderCostService;
	public List<OrderDTO> queryOrderList(OrderDTO orderDTO) {
		
		return orderDaoImpl.queryOrderList(orderDTO);
	}

	public OrderDTO queryOrderDetail(OrderDTO orderDTO) {
		return orderDaoImpl.queryOrder(orderDTO);
	}

	public int updateOrderStatus(OrderDTO orderDTO) throws Exception {
		
		OrderDTO orderTmp = new OrderDTO();
		orderTmp.setId(orderDTO.getId());
		orderTmp = orderDaoImpl.queryOrder(orderTmp);
		//订单不存在直接返回0 修改状态失败
		if(orderTmp == null){
			log.error("order is not exist!");
			return 0;
		}
		
		//判断订单状态是否可以修改
		if(!isCanChangeStatus(orderDTO, orderTmp)){
			log.error("order status from "+orderTmp.getoStatus()+"to"+orderDTO.getoStatus()+"not allow");
			return 0;
		}
		
		if(Dict.order_status_to_section == orderDTO.getoStatus()){
			ProjectDTO projectDTO = new ProjectDTO();
			projectDTO.setId(orderTmp.getoProjectId());
			projectDTO = projectDaoImpl.searchProjectByIdOrCode(projectDTO);
			
			//如果产品未找到 直接返回订单状态失败
			if(projectDTO == null){
				log.error("Product is not exist!");
				return 0;
			}
			int flag = projectDTO.getpExpectSubscriptionAmount().compareTo(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));



			
			log.info(new StringBuffer()
						.append("预期销售额:")
						.append(projectDTO.getpExpectSubscriptionAmount())
						.append("元 ，实际销售额:")
						.append(projectDTO.getpRealSubscriptionAmount())
						.append("元,订单金额")
						.append(orderTmp.getoAmount())
						.append("元").toString()
					);
			//申请订单-金额判断由后台产品销售进度手动控制
			int scaleFlag = projectDTO.getpIssuingScale().compareTo(projectDTO.getpAllSubscriptionAmount().add(orderTmp.getoAmount()));

			//如果预期销售额==实际销售额+当前订单金额 则销售完成   更改实际销售份额为预期销售份额  实际销售额为预期销售额  产品销售状态为已售罄
			//如果预期销售额 > 实际销售额+当前订单金额 则销售完成  更改实际销售额为 实际销售+订单金额  实际销售份额为实际销售份额+订单份额
			if(flag == 0){
				projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));
				projectDTO.setpRealSubscriptionShare(projectDTO.getpExpectSubscriptionShare());
				if(scaleFlag == 0) {
					projectDTO.setpSaleStatus(Dict.pSaleStatus_end);
				}
				projectDTO.setUpdateBy(orderDTO.getUpdateBy());
				projectDTO.setUpdateDate(orderDTO.getUpdateDate());
				projectDaoImpl.updateProject(projectDTO);
			}else if(flag > 0 ){
				projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));
				projectDTO.setpRealSubscriptionShare(projectDTO.getpRealSubscriptionShare().add(orderTmp.getoAmount()));
				projectDTO.setUpdateBy(orderDTO.getUpdateBy());
				projectDTO.setUpdateDate(orderDTO.getUpdateDate());
				projectDaoImpl.updateProject(projectDTO);
			}


			log.info(new StringBuffer()
					.append("本期规模:")
					.append(projectDTO.getpIssuingScale())
					.append("元 ，产品已经销售总额:")
					.append(projectDTO.getpAllSubscriptionAmount())
					.append("元,订单金额")
					.append(orderTmp.getoAmount())
					.append("元").toString());
			if(scaleFlag < 0){
				//超出产品超出预售金额
				return -1;
			}
			
		}
		// 更新为320状态时，往账户余额里充钱
		if(Dict.order_status_rebate ==  orderDTO.getoStatus() && null == orderDTO.getoOwnerId()){
			//成交价为空 直接返回错误
			if(orderDTO.getoTransactionPrice() == null){
				log.error("orderDTO.getoTransactionPrice()  is not exist!");
				return 0;
			}
			BigDecimal common = new BigDecimal(0.01);
			//admin-api-1.1:原来是以返佣金额入账。现在改成成交金额
			
			//获取成交价
			BigDecimal transactionPrice = orderDTO.getoTransactionPrice();
			//计算 成交金额
			BigDecimal transactionRebate = transactionPrice==null?null:transactionPrice.multiply(common).multiply(orderTmp.getoAmount());
			
			orderDTO.setoTransactionRebate(transactionRebate);
			
			log.info("updateOrderStatus order status 返佣 成交价:"+transactionPrice);
			log.info("updateOrderStatus order status 返佣 成交金额:"+transactionRebate);
			
			UserAccountDTO userAccountDTO = new UserAccountDTO();
			
			UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();
			
			
			
			//userAccountDetail.setAmount(orderTmp.getoRebateAmount());
			userAccountDetail.setAmount(orderDTO.getoTransactionRebate());
			userAccountDetail.setFaId(orderTmp.getoFAId());
			userAccountDetail.setCreateBy(orderDTO.getUpdateBy());
			userAccountDetail.setCreateDate(orderDTO.getUpdateDate());
			userAccountDetail.setUpdateBy(orderDTO.getUpdateBy());
			userAccountDetail.setUpdateDate(orderDTO.getUpdateDate());
			userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
			
			userAccountDTO.setUserId(orderTmp.getoFAId());
			
			//userAccountDTO.setAccountBalance(orderTmp.getoRebateAmount());
			//userAccountDTO.setAccountBalanceSleep(orderTmp.getoRebateAmount());
			//userAccountDTO.setAllAccount(orderTmp.getoRebateAmount());
			userAccountDTO.setAccountBalance(orderDTO.getoTransactionRebate());
			userAccountDTO.setAccountBalanceSleep(orderDTO.getoTransactionRebate());
			userAccountDTO.setAllAccount(orderDTO.getoTransactionRebate());
			
			userAccountDTO.setUpdateBy(orderDTO.getUpdateBy());
			userAccountDTO.setUpdateDate(orderDTO.getUpdateDate());
			
			userAccountDaoImpl.addUserAccountDetail(userAccountDetail);
			userAccountDaoImpl.updateUserAccount(userAccountDTO);
		}else{
			orderDTO.setoTransactionPrice(null);
			orderDTO.setoTransactionRebate(null);
		}
		//-------------------
		//admin-api-1.6 新增（20150318）
		//反佣已确认
		//-------------------
		//admin-api-1.13 
		//确认返佣（理财师已经收到返佣的钱）
		//-------------------
		
		log.info("order status :"+orderDTO.getoStatus());
		if(Dict.order_status_confirm_rebate ==  orderDTO.getoStatus()){
			log.info("lisu  @@@@@@@@@@@@@@@@@@@@@2");
			BigDecimal rebateAmount;
			if(orderTmp.getoTransactionRebate() == null){
				rebateAmount = orderTmp.getoRebateAmount();
			}else{
				rebateAmount = orderTmp.getoTransactionRebate();
			}
			UserAccountDTO userAccountDTO = new UserAccountDTO();
			userAccountDTO.setId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
			
			//账户总表变更完成  余额扣除，冻结扣除
			userAccountDTO.setAccountBalance(rebateAmount);
			userAccountDTO.setAccountBalanceSleep(rebateAmount);
			userAccountDTO.setUpdateBy(orderDTO.getUpdateBy());
			userAccountDTO.setUpdateDate(orderDTO.getUpdateDate());
			
			//记录账户明细
			UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();
			userAccountDetail.setAmount(rebateAmount.negate());
			userAccountDetail.setAccountType("02");
			userAccountDetail.setOperateType("07");
			userAccountDetail.setFaId(orderTmp.getoFAId());
			userAccountDetail.setCreateBy(orderDTO.getUpdateBy());
			userAccountDetail.setCreateDate(orderDTO.getUpdateDate());
			userAccountDetail.setUpdateBy(orderDTO.getUpdateBy());
			userAccountDetail.setUpdateDate(orderDTO.getUpdateDate());
			userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
			
			userAccountDaoImpl.insertUserAccountDetail(userAccountDetail);
			userAccountDaoImpl.updateAccountBalanceActivity(userAccountDTO);
		}
		log.info(new StringBuffer()
					.append("order ID:")
					.append(orderDTO.getId())
					.append("  status from ")
					.append(orderTmp.getoStatus())
					.append("  to")
					.append(orderDTO.getoStatus())
					.toString()
					);
		
		int result = orderDaoImpl.updateOrder(orderDTO);
		
		//状态更新成功
		if(result == 1){
			//记录订单流水
			OrderFlowDTO orderFlowDTO = new OrderFlowDTO();
			orderFlowDTO.setFlowDate(new Date());
			orderFlowDTO.setoStatus(orderDTO.getoStatus());
			orderFlowDTO.setCreateBy(orderDTO.getUpdateBy());
			orderFlowDTO.setCreateDate(new Date());
			orderFlowDTO.setUpdateBy(orderDTO.getUpdateBy());
			orderFlowDTO.setUpdateDate(new Date());
			orderFlowDTO.setOrderId(orderDTO.getId());
			
			orderDaoImpl.addOrderFlow(orderFlowDTO);
			
			//发送消息通知
			orderDTO.setoFAId(orderTmp.getoFAId());
			orderDTO.setoProjectId(orderTmp.getoProjectId());
			orderDTO.setoCId(orderTmp.getoCId());
			
			OrderVO orderVo = new OrderVO();
			orderVo.setOrderId(orderDTO.getId());
			List<OrderVO> list  = orderDaoImpl.queryOrderList(orderVo);
			if(list.size()>0){
				try{
					sendMessage(list.get(0));
				}catch(Exception e){
					log.error("send message error!",e);
				}
			
			}
			
		}
		//注入活动信息
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("orderDTO", orderDTO);
		map.put("orderTmp", orderTmp);
		activitesServiceImpl.ActivitiesJobExecution(ActivitiesBusiness.handle_Order_Rebate, map);
		return result;
	}

	public List<OrderVO> queryOrderList(OrderVO orderVo) {
		return orderDaoImpl.queryOrderList(orderVo);
	}

	public int orderCancel(OrderDTO orderDTO) {
		return orderDaoImpl.orderCancel(orderDTO);
	}

	/**
	 * 
	* @Title: sendMessageNote 
	* @Description: 新增站内信息
	* @param @param orderDTO
	* @param @throws SQLException    
	* @return void   
	* @throws
	 */
	private void sendMessageNote(OrderVO orderVo,MessageDTO messageDTO,int id) throws SQLException{
		log.info("Begin send note message!");
		MessageNoteDTO messageNote = new MessageNoteDTO();
		
		messageNote.setCreateBy(messageDTO.getCreateBy());
		messageNote.setCreateDate(messageDTO.getCreateDate());
		messageNote.setUpdateBy(messageDTO.getUpdateBy());
		messageNote.setUpdateDate(messageDTO.getUpdateDate());
		messageNote.setMsgId(messageDTO.getId());
		messageNote.setMsgStatus(Dict.message_note_status);
		messageNote.setStatus(Dict.status_normal);
		messageNote.setFaId(orderVo.getoFAId());
		messageNoteDaoImpl.addMessageNote(messageNote);
		
		log.info("End send note message!");
	}
	
	/**
	 * 
	* @Title: sendMessageSms 
	* @Description: 新增短信信息
	* @param @param orderDTO
	* @param @throws SQLException    
	* @return void   
	* @throws
	 */
	private void sendMessageSms(OrderVO orderVo,MessageDTO messageDTO,int id,String smsType) throws SQLException{
		log.info("Begin send Sms message!");
		MessageSmsDTO messageSmsDTO = new MessageSmsDTO();
		messageSmsDTO.setUpdateBy(messageDTO.getUpdateBy());
		messageSmsDTO.setUpdateDate(messageDTO.getUpdateDate());
		messageSmsDTO.setCreateBy(messageDTO.getCreateBy());
		messageSmsDTO.setCreateDate(messageDTO.getCreateDate());
		messageSmsDTO.setFpSmsContent(messageDTO.getMsgContent());
		messageSmsDTO.setFpSmsMessageId(messageDTO.getId());
		messageSmsDTO.setFpSmsSendType(Dict.message_type_now);
		messageSmsDTO.setStatus(Dict.status_normal);
		messageSmsDTO.setFpSmsType(smsType);
		messageSmsDTO.setFpSmsSendStatus(Dict.message_status_not_send);
		
		FaUserDTO fauser = new FaUserDTO();
		fauser.setId(orderVo.getoFAId());
		
		//查询fa手机号码
		fauser = faUserDaoImpl.getFaUser(fauser);
		
		messageSmsDTO.setFpSmsRecivePhoneNo(fauser.getuLoginName());
		
		messageSmsDaoImpl.addMessageSms(messageSmsDTO);
		
		log.info("End send Sms message!");
	}
	
	/**
	 * 
	* @Title: sendMessage 
	* @Description: 新增订单信息主体
	* @param @param orderDTO
	* @param @throws SQLException    
	* @return void   
	* @throws
	 */
	private void sendMessage(OrderVO orderVo) throws SQLException{

		if(orderVo.getoStatus() == null){
			return;
		}
		
		MessageDTO messageDTO = new MessageDTO();
		
		Map<String, Object> msgMap = new HashMap<String,Object>();
		msgMap.put(Dict.message_client_name, orderVo.getoCName());
		msgMap.put(Dict.message_project_name, orderVo.getoPName());
		msgMap.put(Dict.message_amount, orderVo.getoAmount().divide(new BigDecimal(10000))+"万");
		
		switch (orderVo.getoStatus()) {
			//订单预约成功
			case Dict.order_status_success_per:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 10));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_success_per), msgMap);
				msgMap.put("smsType", Dict.order_130);
				break;
			//订单取消
			case Dict.order_status_cancel:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 3));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_cancel), msgMap);
				msgMap.put("smsType", Dict.order_999);
				break;
			//订单预约失败
			case Dict.order_status_fail_per:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 10));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_fail_per), msgMap);
				msgMap.put("smsType", Dict.order_140);
				break;
			//订单合同已寄出
			case Dict.order_status_contract_mail:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 10));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_contract_mail), msgMap);
				msgMap.put("smsType", Dict.order_210);
				break;
			//订单返佣
			case Dict.order_status_rebate:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 3));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_rebate), msgMap);
				msgMap.put("smsType", Dict.order_320);
				break;
			//订单到款
			case Dict.order_status_to_section:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 3));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_to_section), msgMap);
				msgMap.put("smsType", Dict.order_240);
				break;
			case Dict.order_status_product_set:
				messageDTO.setEndDate(StringUtil.rollDay(orderVo.getUpdateDate(), 3));
				msgMap = MessageUtil.getMessage(Dict.order, String.valueOf(Dict.order_status_product_set), msgMap);
				msgMap.put("smsType", Dict.productSet);
				break;
			default:
				log.info("No message need send!");
				return;
		}
		
		messageDTO.setMsgTitle((String)msgMap.get(Dict.message_title));
		messageDTO.setMsgContent((String)msgMap.get(Dict.message_content));
		messageDTO.setCreateBy(orderVo.getUpdateBy());
		messageDTO.setCreateDate(orderVo.getUpdateDate());
		messageDTO.setUpdateBy(orderVo.getUpdateBy());
		messageDTO.setUpdateDate(orderVo.getUpdateDate());
		messageDTO.setPublicDate(orderVo.getUpdateDate());
		messageDTO.setFaId(orderVo.getoFAId());
		messageDTO.setOrderId(orderVo.getOrderId());
		messageDTO.setClientId(orderVo.getoCId());
		messageDTO.setProductId(orderVo.getoProjectId());
		messageDTO.setStatus(Dict.status_normal);
		messageDTO.setMsgType(Dict.message_type_order);
		messageDTO.setOrderId(orderVo.getOrderId());
		messageDTO.setProductId(orderVo.getoProjectId());
		
		log.info("Add message !");
		int messageId = messageDaoImpl.addMessage(messageDTO);
		
		messageDTO.setId(messageId);
		
		//发送本地信息
		sendMessageNote(orderVo,messageDTO,messageId);
		
		//添加短信
		sendMessageSms(orderVo,messageDTO,messageId,(String)msgMap.get("smsType"));
		
	}
	
	/**
	 * 
	 * @Title: isCanChangeStatus
	 * @Description: 判断订单状态是否能修改 
	 * @param @param order
	 * @param @param orderTmp
	 * @param @return   
	 * @return boolean   
	 * @throws
	 */
	private boolean isCanChangeStatus(OrderDTO order,OrderDTO orderTmp){
		
		int oldOrderStatus = orderTmp.getoStatus();
		int newOrderStatus = order.getoStatus();
		
		
		if((oldOrderStatus == 120||oldOrderStatus == 110)&&newOrderStatus==121){
			return true;
		}
		
		if(oldOrderStatus == 121&& newOrderStatus==123){
			return true;
		}
		
		if(oldOrderStatus==123 && newOrderStatus==124){
			return true;
		}
		
		if(oldOrderStatus <= 124&& newOrderStatus==130){
			return true;
		}
		
		if(oldOrderStatus < 130 && newOrderStatus==140){
			return true;
		}
		
		if(oldOrderStatus == 130 && newOrderStatus == 210){
			return true;
		}
		//新增
		//合同已寄出 - 已打款
		if(oldOrderStatus == 210 && newOrderStatus == 220){
			return true;
		}
		
		if((oldOrderStatus == 220 || oldOrderStatus == 230) && newOrderStatus == 240){
			return true;
		}
		
		if(oldOrderStatus == 250 && newOrderStatus==310){
			return true;
		}
		
		if(oldOrderStatus == 310 && newOrderStatus == 311){
			return true;
		}
		
		if(oldOrderStatus == 311 && newOrderStatus == 312){
			return true;
		}
		
		if(oldOrderStatus == 312 && newOrderStatus == 313){
			return true;
		}
		
		if(oldOrderStatus == 313 && newOrderStatus == 314){
			return true;
		}
		
		if((oldOrderStatus <= 314 || oldOrderStatus >=250) && newOrderStatus == 320){
			return true;
		}
		//新增
		//已返佣- 反佣已确认
		if(oldOrderStatus == 320 && newOrderStatus == 330){
			return true;
		}
		if(oldOrderStatus < 250 && newOrderStatus == 999){
			return true;
		}
		return false;
	}

	@Override
	public int queryOrderAllInfoCount(OrderVO orderVo) throws Exception {
		return orderDaoImpl.queryOrderAllInfoCount(orderVo);
	}

	@Override
	public int updateOrderDefriendStatus(OrderDTO orderDTO) throws Exception {
		int result = orderDaoImpl.updateOrderDefriendStatus(orderDTO);
		
		//注入活动信息
		try {
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("orderDTO", orderDTO);
			map.put("updateInt", result);
			activitesServiceImpl.ActivitiesJobExecutionObject(ActivitiesBusinessObject.handle_Order_Defriend, map);
		} catch (Exception e) {
			log.error("updateProject ActivitiesJobExecutionObejct error", e);
		}
		return result;
	}

	@Override
	public List<HashMap<String, String>> queryOrderByProIdList(OrderVO orderDTO) throws SQLException {
		return orderDaoImpl.queryOrderByProIdList(orderDTO);
	}

	@Override
	public int countOrderByProIdList(OrderVO orderDTO) throws SQLException {
		return orderDaoImpl.countOrderByProIdList(orderDTO);
	}
	
	@Override
	public List<OrderDTO> queryInfoByOrderIds(String ids) throws SQLException{
		return orderDaoImpl.queryInfoByOrderIds(ids);
	}

	@Override
	public int queryOrderFollowUpAllInfoCount(OrderVO orderVo) throws SQLException {
		return orderDaoImpl.queryOrderFollowUpAllInfoCount(orderVo);
	}

	@Override
	public List<OrderVO> queryOrderFollowUpList(OrderVO orderVo) throws SQLException {
		return orderDaoImpl.queryOrderFollowUpList(orderVo);
	}

	@Override
	public OrderByGaiZaoDTO queryOrderDetailByGaiZao(	OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		return orderDaoImpl.queryOrderByGaiZao(orderByGaiZaoDTO).get(0);
	}
	
	@Override
	public int queryOrderCountByGaiZao(
			OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		return orderDaoImpl.queryOrderCountByGaiZao(orderByGaiZaoDTO);
	}
	@Override
	public List<OrderByGaiZaoDTO> queryOrderListByGaiZao(
			OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		return orderDaoImpl.queryOrderListByGaiZao(orderByGaiZaoDTO);
	}
	
	@Override
	public int updateOrderStatusByGaiZao(OrderByGaiZaoDTO orderDTO) throws Exception {
			
			OrderByGaiZaoDTO orderTmp = new OrderByGaiZaoDTO();
			orderTmp.setId(orderDTO.getId());
			orderTmp = orderDaoImpl.queryOrderBaseInfoByGaiZao(orderTmp).get(0);
			//订单不存在直接返回0 修改状态失败
			if(orderTmp == null){
				log.error("order is not exist!");
				return 0;
			}
			// 240 已确认打款
			if(null != orderDTO.getoStatus() && Dict.order_status_to_section == orderDTO.getoStatus()){
				ProjectDTO projectDTO = new ProjectDTO();
				projectDTO.setId(orderTmp.getoProjectId());
				projectDTO = projectDaoImpl.searchProjectByIdOrCode(projectDTO);

				//如果产品未找到 直接返回订单状态失败
				if(projectDTO == null){
					log.error("Product is not exist!");
					return 0;
				}

				int flag = projectDTO.getpExpectSubscriptionAmount().compareTo(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));
				
				log.info(new StringBuffer()
							.append("预期销售额:")
							.append(projectDTO.getpExpectSubscriptionAmount())
							.append("元 ，实际销售额:")
							.append(projectDTO.getpRealSubscriptionAmount())
							.append("元,订单金额")
							.append(orderTmp.getoAmount())
							.append("元").toString()
						);
				//如果预期销售额==实际销售额+当前订单金额 则销售完成   更改实际销售份额为预期销售份额  实际销售额为预期销售额  产品销售状态为已售罄
				//如果预期销售额 > 实际销售额+当前订单金额 则销售完成  更改实际销售额为 实际销售+订单金额  实际销售份额为实际销售份额+订单份额
				if(flag == 0){
					projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));
					projectDTO.setpRealSubscriptionShare(projectDTO.getpExpectSubscriptionShare());
					projectDTO.setpSaleStatus(Dict.pSaleStatus_end);
					projectDTO.setUpdateBy(orderDTO.getUpdateBy());
					projectDTO.setUpdateDate(orderDTO.getUpdateDate());
					projectDaoImpl.updateProject(projectDTO);
				}else if(flag > 0 ){
					projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderTmp.getoAmount()));
					projectDTO.setpRealSubscriptionShare(projectDTO.getpRealSubscriptionShare().add(orderTmp.getoAmount()));
					projectDTO.setUpdateBy(orderDTO.getUpdateBy());
					projectDTO.setUpdateDate(orderDTO.getUpdateDate());
					projectDaoImpl.updateProject(projectDTO);
				}else{
					//超出产品超出预售金额
					return -1;
				}
				// 确认到款后 判断有无后端
				if(null != orderTmp.getoBackTransactionRebate()){
					if(orderTmp.getoBackTransactionRebate().compareTo(new BigDecimal(0)) <= 0){
						// 无后端
						orderDTO.setoBackStatus(361);
					}else{
						// 有后端
						orderDTO.setoBackStatus(241);
					}
				}else{
					// 无后端
					orderDTO.setoBackStatus(361);
				}
				
			}
			// ========开始区分前后端========
			// 320 前端返佣 321 后端结拥
			if((null != orderDTO.getoStatus() && Dict.order_status_rebate ==  orderDTO.getoStatus()) || 
					(null != orderDTO.getoBackStatus() && Dict.order_status_back_rebate ==  orderDTO.getoBackStatus())){
				// admin-api-1.1:原来是以返佣金额入账。现在改成成交金额
				// 成交价
				BigDecimal transactionPrice = null != orderTmp.getoTransactionPrice()?orderTmp.getoTransactionPrice():orderTmp.getoBackTransactionPrice();
				// 成交金额
				BigDecimal transactionRebate =null != orderTmp.getoTransactionRebate()?orderTmp.getoTransactionRebate():orderTmp.getoBackTransactionRebate();
				
				log.info("updateOrderStatus order status 返佣 成交价:"+transactionPrice);
				log.info("updateOrderStatus order status 返佣 成交金额:"+transactionRebate);
				
				UserAccountDTO userAccountDTO = new UserAccountDTO();
				
				UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();
				
				userAccountDetail.setAmount(orderTmp.getoTransactionRebate());
				userAccountDetail.setFaId(orderTmp.getoFAId());
				userAccountDetail.setCreateBy(orderTmp.getUpdateBy());
				userAccountDetail.setCreateDate(orderTmp.getUpdateDate());
				userAccountDetail.setUpdateBy(orderTmp.getUpdateBy());
				userAccountDetail.setUpdateDate(orderTmp.getUpdateDate());
				userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
				userAccountDTO.setUserId(orderTmp.getoFAId());
				userAccountDTO.setAccountBalance(orderTmp.getoTransactionRebate());
				userAccountDTO.setAccountBalanceSleep(orderTmp.getoTransactionRebate());
				userAccountDTO.setAllAccount(orderTmp.getoTransactionRebate());
				userAccountDTO.setUpdateBy(orderTmp.getUpdateBy());
				userAccountDTO.setUpdateDate(orderTmp.getUpdateDate());
				
				userAccountDaoImpl.addUserAccountDetail(userAccountDetail);
				userAccountDaoImpl.updateUserAccount(userAccountDTO);
				// 有单模式&&前端结佣 财务结佣后 佣金明细可提现
				// add 非有单订单可线上自提佣金 区分前后端
				YouDanAmountDTO youDanAmountDTO = new YouDanAmountDTO();
				youDanAmountDTO.setAssociationId(orderDTO.getId());
				youDanAmountDTO.setOperateType("02");//操作类型 02：可提现
				youDanAmountDTO.setUpdateBy(orderTmp.getUpdateBy());
				youDanAmountDTO.setUpdateDate(new Date());
				// 财务确认返佣后 有单、非有单前端金额 = 财务前端佣金 + 活动打款 + 其他打款额
//				BigDecimal getoActivityAmount = orderDTO.getoActivityAmount();
//				if(getoActivityAmount==null){
//					log.info("getoActivityAmount:"+getoActivityAmount);
//					getoActivityAmount=new BigDecimal(0);
//				}
//				BigDecimal getoFinanceOtherAmount = orderDTO.getoFinanceOtherAmount();
//				if(getoFinanceOtherAmount==null){
//					log.info("getoFinanceOtherAmount:"+getoFinanceOtherAmount);
//					getoFinanceOtherAmount=new BigDecimal(0);
//				}
//				BigDecimal getoFinanceFrontRebate = orderDTO.getoFinanceFrontRebate();
//				if(getoFinanceFrontRebate==null){
//					log.info("getoFinanceFrontRebate:"+getoFinanceFrontRebate);
//					getoFinanceFrontRebate=new BigDecimal(0);
//				}
//				youDanAmountDTO.setAmount(getoFinanceFrontRebate.add(getoActivityAmount.add(getoFinanceOtherAmount)));
				
				// 有单订单-自提
				// add 线下打款
				if(null != orderTmp.getoOwnerId() && (null != orderDTO.getoStatus() && Dict.order_status_rebate ==  orderDTO.getoStatus())){
					youDanAmountDTO.setAmount(orderDTO.getoFinanceFrontRebate().add(orderDTO.getoActivityAmount().add(orderDTO.getoFinanceOtherAmount())));
					// add 有单订单也可线下打款
					if("1".equals(orderDTO.getoYouDanRebateType())){
						// 自提
						youDanAmountDTO.setAmountType("02");//金额类型 02有单佣金',
						// 线上自提- lisu
//						paymentServiceImpl.addPaymentForOrderRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_NEW);
					}else{
						// 线下打款- lisu
						paymentServiceImpl.addPaymentForOrderRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_SUCC);
						// 提现表中OPERATE_TYPE状态变更为 08：线下打款
						youDanAmountDTO.setOperateType("08");//操作类型 08：线下打款
						youDanAmountDTO.setAmountType("02");//金额类型 02有单佣金'
					}
				// 非有单订单-前端佣金
				}else if(null == orderTmp.getoOwnerId() && (null != orderDTO.getoStatus() && Dict.order_status_rebate ==  orderDTO.getoStatus())){
					//非有单前端佣金 = 财务前端佣金 + 活动打款 + 其他打款额
					youDanAmountDTO.setAmount(orderDTO.getoFinanceFrontRebate().add(orderDTO.getoActivityAmount().add(orderDTO.getoFinanceOtherAmount())));
					if("1".equals(orderDTO.getoRebateType())){
						// 自提
						youDanAmountDTO.setAmountType("03");//金额类型 03非有单前端佣金',
						// 线上自提- lisu
//						paymentServiceImpl.addPaymentForOrderRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_NEW);
					}else{
						// 线下打款- lisu
						paymentServiceImpl.addPaymentForOrderRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_SUCC);
						// 提现表中OPERATE_TYPE状态变更为 08：线下打款
						youDanAmountDTO.setOperateType("08");//操作类型 08：线下打款
						youDanAmountDTO.setAmountType("03");//金额类型 02非有单前端佣金'
					}
				// 非有单订单-后端佣金	
				}else if(null == orderTmp.getoOwnerId() && (null != orderDTO.getoBackStatus() && Dict.order_status_back_rebate ==  orderDTO.getoBackStatus())){
					// 非有单后端佣金 = 财务后端佣金
					youDanAmountDTO.setAmount(orderDTO.getoFinanceBackRebate());
					if("1".equals(orderDTO.getoBackRebateType())){
						// 自提
						youDanAmountDTO.setAmountType("04");//金额类型 03非有单后端佣金',
						// 线上自提- lisu
//						paymentServiceImpl.addPaymentForOrderRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_NEW);
					}else{
						// 线下打款- lisu
						paymentServiceImpl.addPaymentForOrderBackRebate(orderDTO,orderTmp, BizEnums.PayEnums.PAY_STATUS_SUCC);
						// 提现表中OPERATE_TYPE状态变更为 08：线下打款
						youDanAmountDTO.setOperateType("08");//操作类型 08：线下打款
						youDanAmountDTO.setAmountType("04");//金额类型 03非有单后端佣金
						
					}
				}
				if(null != youDanAmountDTO.getAmountType()){
					youDanAmountDaoImpl.updateYouDanAmount(youDanAmountDTO);
				}
			}
			
			log.info("order status :"+orderDTO.getoStatus());
			// 330-前端确认佣金到账 331-后端确认佣金到账
			if((null != orderDTO.getoStatus() && Dict.order_status_confirm_rebate ==  orderDTO.getoStatus()) ||
					(null != orderDTO.getoBackStatus() && Dict.order_status_back_confirm_rebate ==  orderDTO.getoBackStatus())){
				log.info("lisu  @@@@@@@@@@@@@@@@@@@@@2");
				BigDecimal rebateAmount;
				// 判断是前端还是后端
				if(null !=orderDTO.getoStatus()){
					rebateAmount = orderTmp.getoTransactionRebate() == null?orderTmp.getoRebateAmount():orderTmp.getoTransactionRebate();
				}else{
					rebateAmount = orderTmp.getoBackTransactionRebate() == null?orderTmp.getoBackRebateAmount():orderTmp.getoBackTransactionRebate();
				}
				
				UserAccountDTO userAccountDTO = new UserAccountDTO();
				userAccountDTO.setId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
				
				//账户总表变更完成  余额扣除，冻结扣除
				userAccountDTO.setAccountBalance(rebateAmount);
				userAccountDTO.setAccountBalanceSleep(rebateAmount);
				userAccountDTO.setUpdateBy(orderDTO.getUpdateBy());
				userAccountDTO.setUpdateDate(orderDTO.getUpdateDate());
				
				//记录账户明细
				UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();
				userAccountDetail.setAmount(rebateAmount.negate());
				userAccountDetail.setAccountType("02");
				userAccountDetail.setOperateType("07");
				userAccountDetail.setFaId(orderTmp.getoFAId());
				userAccountDetail.setCreateBy(orderDTO.getUpdateBy());
				userAccountDetail.setCreateDate(orderDTO.getUpdateDate());
				userAccountDetail.setUpdateBy(orderDTO.getUpdateBy());
				userAccountDetail.setUpdateDate(orderDTO.getUpdateDate());
				userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderTmp.getoFAId()));
				
				userAccountDaoImpl.insertUserAccountDetail(userAccountDetail);
				userAccountDaoImpl.updateAccountBalanceActivity(userAccountDTO);
			}
			/**
			 * 预约相关
			 * 提现表插入数据
			 * 有单、非有单前后端
			 */
			YouDanAmountDTO youDanAmountDTO = new YouDanAmountDTO();
			// 入库有单金额明细表基础参数
			youDanAmountDTO.setAmount(orderTmp.getoYouDanRebate());
			youDanAmountDTO.setCreateBy(orderTmp.getCreateBy());
			youDanAmountDTO.setCreateDate(new Date());
			youDanAmountDTO.setUpdateBy(orderTmp.getUpdateBy());
			youDanAmountDTO.setUpdateDate(new Date());
			youDanAmountDTO.setFaId(orderTmp.getoFAId());//关联FAID
			
			// 130 预约成功 有单金额明细表 增加佣金冻结
			if(null!= orderDTO.getoStatus() && Dict.order_status_success_per == orderDTO.getoStatus()){
				// 有单返佣
				if(null != orderTmp.getoYouDanRebate()){
					youDanAmountDTO.setAmountType("02");//金额类型 02佣金',
					youDanAmountDTO.setAssociationId(orderTmp.getId());
					youDanAmountDTO.setOperateType("01");//操作类型 01：冻结
					youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
				}else {
					// 非有单前端返佣
					if(null != orderTmp.getoRebateRate()){
						youDanAmountDTO.setAmountType("03");//金额类型 03 非有单前端佣金',
						youDanAmountDTO.setAssociationId(orderTmp.getId());
						youDanAmountDTO.setOperateType("01");//操作类型 01：冻结
						youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
					}
					// 非有单后端返佣
					if(null != orderTmp.getoBackRebateRate()){
						youDanAmountDTO.setAmountType("04");//金额类型 04 非有单后端佣金',
						youDanAmountDTO.setAssociationId(orderTmp.getId());
						youDanAmountDTO.setOperateType("01");//操作类型 01：冻结
						youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
					}
				}
				
				
			// 140 预约失败 有单金额明细表 增加佣金失败
			}else if(null!= orderDTO.getoStatus() && Dict.order_status_fail_per == orderDTO.getoStatus()){
				// 有单返佣
				if(null != orderTmp.getoYouDanRebate()){
					youDanAmountDTO.setAmountType("02");//金额类型 02佣金',
					youDanAmountDTO.setAssociationId(orderTmp.getId());
					youDanAmountDTO.setOperateType("06");//操作类型 06：失败
					youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
				}else {
					// 非有单-前端返佣
					if(null != orderTmp.getoRebateRate()){
						youDanAmountDTO.setAmountType("03");//金额类型 04 非有单前端佣金',
						youDanAmountDTO.setAssociationId(orderTmp.getId());
						youDanAmountDTO.setOperateType("06");//操作类型 06：失败
						youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
					}
					// 非有单-后端返佣
					if(null != orderTmp.getoBackRebateRate()){
						youDanAmountDTO.setAmountType("04");//金额类型 05 非有单后端佣金',
						youDanAmountDTO.setAssociationId(orderTmp.getId());
						youDanAmountDTO.setOperateType("06");//操作类型 06：失败
						youDanAmountDaoImpl.insertYouDanAmount(youDanAmountDTO);
					}
				}
			}
			
			
			log.info(new StringBuffer()
						.append("order ID:")
						.append(orderDTO.getId())
						.append("  status from ")
						.append(orderTmp.getoStatus())
						.append("  to")
						.append(orderDTO.getoStatus())
						.toString()
						);
			// 更新订单状态
			int result = orderDaoImpl.updateOrderByGaiZao(orderDTO);
			
			//状态更新成功
			if(result == 1){
				//记录订单流水
				OrderFlowDTO orderFlowDTO = new OrderFlowDTO();
				orderFlowDTO.setFlowDate(new Date());
				orderFlowDTO.setoStatus(orderDTO.getoStatus());
				orderFlowDTO.setoBackStatus(orderDTO.getoBackStatus());
				orderFlowDTO.setCreateBy(orderDTO.getUpdateBy());
				orderFlowDTO.setCreateDate(new Date());
				orderFlowDTO.setUpdateBy(orderDTO.getUpdateBy());
				orderFlowDTO.setUpdateDate(new Date());
				orderFlowDTO.setOrderId(orderDTO.getId());
				
				orderDaoImpl.addOrderFlow(orderFlowDTO);
				
				//发送消息通知
				orderDTO.setoFAId(orderTmp.getoFAId());
				orderDTO.setoProjectId(orderTmp.getoProjectId());
				orderDTO.setoCId(orderTmp.getoCId());
				
				OrderVO orderVo = new OrderVO();
				orderVo.setOrderId(orderDTO.getId());
				List<OrderVO> list  = orderDaoImpl.queryOrderList(orderVo);
				if(list.size()>0){
					try{
						sendMessage(list.get(0));
					}catch(Exception e){
						log.error("send message error!",e);
					}
				
				}
				
			}
			//注入活动信息
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("orderDTO", orderDTO);
			map.put("orderTmp", orderTmp);
			activitesServiceImpl.ActivitiesJobExecution(ActivitiesBusiness.handle_Order_Rebate, map);
			return result;
		}
	
	@Override
	public List<OrderManagerUserVO> queryOrderOwnerUserList()
			throws SQLException {
		return orderDaoImpl.queryOrderOwnerUserList();
	}

	@Override
	public List<OrderByGaiZaoDTO> queryOrderBaseInfoByGaiZao(OrderByGaiZaoDTO orderByGaiZaoDTO) throws SQLException {
		return orderDaoImpl.queryOrderBaseInfoByGaiZao(orderByGaiZaoDTO);
	}

	@Override
	public void updateOrderStatusNow(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus130(OrderByGaiZaoDTO orderDTO,OrderVO orderVo) throws SQLException {

		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);

	}

	@Override
	public void updateOrderStatus120(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	public void updateOrderStatus888(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus220(OrderByGaiZaoDTO orderDTO, OrderVO orderVo,FpOrderCostDTO fpOrderCost) throws SQLException {

		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		// 添加/修改  订单  费用信息(添加结佣信息)\
		saveOrderCost(orderDTO, orderVo, fpOrderCost, Dict.OrderCostDTO.STATUS_QD_JY);

		// 修改订单 信息 （状态、成交价）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	private void saveOrderCost(OrderByGaiZaoDTO orderDTO, OrderVO orderVo, FpOrderCostDTO fpOrderCost, String costType) throws SQLException {

		FpOrderCostDTO fpOrderCostTmp = new FpOrderCostDTO();
		fpOrderCostTmp.setOrderId(orderDTO.getId());
		fpOrderCostTmp.setCostType("\""+costType+"\"");
		fpOrderCostTmp.setDeleteTag("1");
		fpOrderCostTmp = fpOrderCostService.queryListGetFirst(fpOrderCostTmp);

		if(fpOrderCostTmp == null || fpOrderCostTmp.getId() == null || costType.indexOf(Dict.OrderCostDTO.STATUS_HD_SYJK) >= 0 || costType.indexOf(Dict.OrderCostDTO.STATUS_HD_CWJY) >= 0 ){
			//添加
			fpOrderCost.setId(null);
			fpOrderCost.setOrderId(orderDTO.getId());
			fpOrderCost.setCostType(costType);
			if(fpOrderCost.getCostAmount() == null) {
				fpOrderCost.setCostAmount(orderVo.getoTransactionRebate());
			}

			//获取绑定关系
			if(costType.indexOf(Dict.OrderCostDTO.STATUS_HD_CWJY) >= 0){
				FpOrderCostDTO query = new FpOrderCostDTO();
				query.setOrderId(orderDTO.getId());
				query.setDeleteTag("1");
				query.setCostStatus("start");
				query.setCostType("\""+Dict.OrderCostDTO.STATUS_HD_JY+"\",\""+Dict.OrderCostDTO.STATUS_HD_HDFH+"\",\""+Dict.OrderCostDTO.STATUS_HD_TX+"\",\""+Dict.OrderCostDTO.STATUS_HD_SCBT+"\",\""+Dict.OrderCostDTO.STATUS_HD_OTHER+"\"");
				query = fpOrderCostService.queryListGetFirst(query);

				if(query != null) {
					fpOrderCost.setRelatedId(query.getId()+"");
				}
			}


			fpOrderCostService.insert(fpOrderCost);
		}else{
			//修改
			fpOrderCost.setId(fpOrderCostTmp.getId());
			fpOrderCostService.update(fpOrderCost);
		}


	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public ResultMap updateOrderStatus240(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		ResultMap resultMap = new ResultMap();

		ProjectDTO projectDTO = new ProjectDTO();
		projectDTO.setId(orderVo.getoProjectId());
		projectDTO = projectDaoImpl.searchProjectByIdOrCode(projectDTO);

		//如果产品未找到 直接返回订单状态失败
		if(projectDTO == null){
			log.error("Product is not exist!");
			resultMap.setStatus(ResultMap.STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.STATUS_CODE_PRODUCT_NOTEXIST);
			return resultMap;
		}

		int flag = projectDTO.getpExpectSubscriptionAmount().compareTo(projectDTO.getpRealSubscriptionAmount().add(orderVo.getoAmount()));

		log.info(new StringBuffer()
				.append("预期销售额:")
				.append(projectDTO.getpExpectSubscriptionAmount())
				.append("元 ，实际销售额:")
				.append(projectDTO.getpRealSubscriptionAmount())
				.append("元,订单金额")
				.append(orderVo.getoAmount())
				.append("元").toString()
		);
		//如果预期销售额==实际销售额+当前订单金额 则销售完成   更改实际销售份额为预期销售份额  实际销售额为预期销售额  产品销售状态为已售罄
		//如果预期销售额 > 实际销售额+当前订单金额 则销售完成  更改实际销售额为 实际销售+订单金额  实际销售份额为实际销售份额+订单份额
		if(flag == 0){
			projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderVo.getoAmount()));
			projectDTO.setpRealSubscriptionShare(projectDTO.getpExpectSubscriptionShare());
			projectDTO.setpSaleStatus(Dict.pSaleStatus_end);
			projectDTO.setUpdateBy(orderDTO.getUpdateBy());
			projectDTO.setUpdateDate(orderDTO.getUpdateDate());
			projectDaoImpl.updateProject(projectDTO);
		}else if(flag > 0 ){
			projectDTO.setpRealSubscriptionAmount(projectDTO.getpRealSubscriptionAmount().add(orderVo.getoAmount()));
			projectDTO.setpRealSubscriptionShare(projectDTO.getpRealSubscriptionShare().add(orderVo.getoAmount()));
			projectDTO.setUpdateBy(orderDTO.getUpdateBy());
			projectDTO.setUpdateDate(orderDTO.getUpdateDate());
			projectDaoImpl.updateProject(projectDTO);
		}else{
			//超出产品超出预售金额
			resultMap.setStatus(ResultMap.STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.STATUS_CODE_2305);
			return resultMap;
		}

		//有无后端-改版后是手动  申请后端结佣，不是根据后端价格判断
		// 确认到款后 判断有无后端
/*		if(null != orderTmp.getoBackTransactionRebate()){
			if(orderTmp.getoBackTransactionRebate().compareTo(new BigDecimal(0)) <= 0){
				// 无后端
				orderDTO.setoBackStatus(361);
			}else{
				// 有后端
				orderDTO.setoBackStatus(241);
			}
		}else{
			// 无后端
			orderDTO.setoBackStatus(361);
		}*/


		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);

		resultMap.setStatus(ResultMap.STATUS.SUCCESS);
		resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);

		return resultMap;
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus310(OrderByGaiZaoDTO orderDTO, OrderVO orderVo, FpOrderCostDTO fpOrderCost) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		// 添加  订单  费用信息(添加结佣信息)
		saveOrderCost(orderDTO, orderVo, fpOrderCost, Dict.OrderCostDTO.STATUS_QD_SYJK);

		// 修改订单 信息 （状态、成交价）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus320(OrderByGaiZaoDTO orderDTO, OrderVO orderVo, FpOrderCostDTO fpOrderCost) throws SQLException {

		// 账户明细表 admin-api-1.1:原来是以返佣金额入账。现在改成成交金额
		// 成交价
		BigDecimal transactionPrice = orderVo.getoTransactionPrice();
		// 成交金额
		BigDecimal transactionRebate = orderVo.getoTransactionRebate();

		log.info("updateOrderStatus order status 返佣 成交价:"+transactionPrice);
		log.info("updateOrderStatus order status 返佣 成交金额:"+transactionRebate);

		UserAccountDTO userAccountDTO = new UserAccountDTO();

		UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();

		userAccountDetail.setAmount(orderVo.getoTransactionRebate());
		userAccountDetail.setFaId(orderVo.getoFAId());
		userAccountDetail.setCreateBy(orderVo.getUpdateBy());
		userAccountDetail.setCreateDate(orderVo.getUpdateDate());
		userAccountDetail.setUpdateBy(orderVo.getUpdateBy());
		userAccountDetail.setUpdateDate(orderVo.getUpdateDate());
		userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderVo.getoFAId()));
		userAccountDTO.setUserId(orderVo.getoFAId());
		userAccountDTO.setAccountBalance(orderVo.getoTransactionRebate());
		userAccountDTO.setAccountBalanceSleep(orderVo.getoTransactionRebate());
		userAccountDTO.setAllAccount(orderVo.getoTransactionRebate());
		userAccountDTO.setUpdateBy(orderVo.getUpdateBy());
		userAccountDTO.setUpdateDate(orderVo.getUpdateDate());

		userAccountDaoImpl.addUserAccountDetail(userAccountDetail);
		userAccountDaoImpl.updateUserAccount(userAccountDTO);

		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		// 添加  订单  费用信息(添加结佣信息)
		saveOrderCost(orderDTO, orderVo, fpOrderCost, Dict.OrderCostDTO.STATUS_QD_CWJY);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus330(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		BigDecimal rebateAmount  = orderVo.getoTransactionRebate() == null?orderVo.getoRebateAmount():orderVo.getoTransactionRebate();

		UserAccountDTO userAccountDTO = new UserAccountDTO();
		userAccountDTO.setId(userAccountDaoImpl.getUserAccountId(orderVo.getoFAId()));

		//账户总表变更完成  余额扣除，冻结扣除
		userAccountDTO.setAccountBalance(rebateAmount);
		userAccountDTO.setAccountBalanceSleep(rebateAmount);
		userAccountDTO.setUpdateBy(orderDTO.getUpdateBy());
		userAccountDTO.setUpdateDate(orderDTO.getUpdateDate());

		//记录账户明细
		UserAccountDetailDTO userAccountDetail = new UserAccountDetailDTO();
		userAccountDetail.setAmount(rebateAmount.negate());
		userAccountDetail.setAccountType("02");
		userAccountDetail.setOperateType("07");
		userAccountDetail.setFaId(orderVo.getoFAId());
		userAccountDetail.setCreateBy(orderDTO.getUpdateBy());
		userAccountDetail.setCreateDate(orderDTO.getUpdateDate());
		userAccountDetail.setUpdateBy(orderDTO.getUpdateBy());
		userAccountDetail.setUpdateDate(orderDTO.getUpdateDate());
		userAccountDetail.setAccountId(userAccountDaoImpl.getUserAccountId(orderVo.getoFAId()));

		userAccountDaoImpl.insertUserAccountDetail(userAccountDetail);
		userAccountDaoImpl.updateAccountBalanceActivity(userAccountDTO);

		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);

	}

	@Override
	@Transactional(rollbackFor=Exception.class)
	public void updateOrderStatus360(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {

		//判断
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  status from ")
				.append(orderVo.getoStatus())
				.append("  to")
				.append(orderDTO.getoStatus())
				.toString()
		);
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	public void updateOrderBackStatus241(OrderByGaiZaoDTO orderDTO, OrderVO orderVo, FpOrderCostDTO fpOrderCost) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);

		// 添加  订单  费用信息(添加结佣信息)
		if(!StringUtils.isBlank(fpOrderCost.getCostType())) {

			fpOrderCost.setCostStatus("start");
			saveOrderCost(orderDTO, orderVo, fpOrderCost, fpOrderCost.getCostType());
		}

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	public void updateOrderBackStatus231(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);

		//删除 订单费用信息   - 查询未完成
		updateDeleteTagOrStatus(orderDTO,false);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	private void updateDeleteTagOrStatus(OrderByGaiZaoDTO orderDTO,boolean isStatus) throws SQLException {
		FpOrderCostDTO fpOrderCostTmp = new FpOrderCostDTO();
		fpOrderCostTmp.setOrderId(orderDTO.getId());
		fpOrderCostTmp.setCostType("\""+ Dict.OrderCostDTO.STATUS_HD_JY+"\",\"" + Dict.OrderCostDTO.STATUS_HD_CWJY + "\",\""+Dict.OrderCostDTO.STATUS_HD_SYJK+"\"," +
				"\"" + Dict.OrderCostDTO.STATUS_HD_HDFH + "\",\"" + Dict.OrderCostDTO.STATUS_HD_TX + "\",\"" + Dict.OrderCostDTO.STATUS_HD_SCBT + "\",\"" + Dict.OrderCostDTO.STATUS_HD_OTHER + "\"");
		fpOrderCostTmp.setCostStatus("start");
		fpOrderCostTmp.setDeleteTag("1");
		List<FpOrderCostDTO> fpOrderCostTmpList = fpOrderCostService.queryList(fpOrderCostTmp);

		for ( FpOrderCostDTO orderCost : fpOrderCostTmpList){

			if(isStatus){
				orderCost.setCostStatus("end");
			}else{
				orderCost.setDeleteTag("2");
			}
			fpOrderCostService.update(orderCost);
		}
	}

	@Override
	public void updateOrderBackStatus261(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	public void updateOrderBackStatus311(OrderByGaiZaoDTO orderDTO, OrderVO orderVo,FpOrderCostDTO fpOrderCost) throws SQLException {

		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);

		// 添加  订单  费用信息(添加结佣信息)
		fpOrderCost.setCostStatus("start");
		saveOrderCost(orderDTO, orderVo, fpOrderCost, Dict.OrderCostDTO.STATUS_HD_SYJK);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo,fpOrderCost);
	}

	@Override
	public void updateOrderBackStatus321(OrderByGaiZaoDTO orderDTO, OrderVO orderVo,FpOrderCostDTO fpOrderCost) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);
/*		FpOrderCostDTO fpOrderCostTmp = new FpOrderCostDTO();
		fpOrderCostTmp.setOrderId(orderDTO.getId());
		fpOrderCostTmp.setCostType("\""+ Dict.OrderCostDTO.STATUS_HD_JY+"\",\"" + Dict.OrderCostDTO.STATUS_HD_HDFH + "\",\"" + Dict.OrderCostDTO.STATUS_HD_TX + "\",\"" + Dict.OrderCostDTO.STATUS_HD_SCBT + "\",\"" + Dict.OrderCostDTO.STATUS_HD_OTHER + "\"");
		fpOrderCostTmp.setCostStatus("start");
		fpOrderCostTmp.setDeleteTag("1");

		FpOrderCostDTO fpOrderCostTmpList = fpOrderCostService.queryListGetFirst(fpOrderCostTmp);*/

		// 添加  订单  费用信息(添加结佣信息)
		saveOrderCost(orderDTO, orderVo, fpOrderCost,Dict.OrderCostDTO.STATUS_HD_CWJY);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
	public void updateOrderBackStatus331(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		//状态  流转   日志打印
		log.info(new StringBuffer()
				.append("order ID:")
				.append(orderDTO.getId())
				.append("  BackStatus from ")
				.append(orderVo.getoBackStatus())
				.append("  to")
				.append(orderDTO.getoBackStatus())
				.toString()
		);

		// 订单费用信息   - 状态结束
		updateDeleteTagOrStatus(orderDTO,true);

		// 修改订单 信息 （状态）
		updateOrderAndFlow(orderDTO, orderVo);
	}

	@Override
    public List<OrderFlowDTO> queryOrderFlowList(String orderId) throws SQLException {
        return orderDaoImpl.queryOrderFlowList(orderId);
    }

	@Override
	public void updateOrder(OrderByGaiZaoDTO orderDTO) throws SQLException {
		// 更新订单状态
		orderDaoImpl.updateOrderByGaiZao(orderDTO);
	}

	@Override
	public void updateOrderFlow(OrderFlowDTO orderFlowDTO) throws SQLException {
		orderDaoImpl.updateOrderFlow(orderFlowDTO);
	}

	@Override
	public Map<String,Object> queryOrderMaxMinDateByProductId(Integer integer) throws SQLException {
			return orderDaoImpl.queryOrderMaxMinDateByProductId(integer);
	}

	@Override
	public List<String> queryFaUserOrder() throws SQLException {
		return orderDaoImpl.queryFaUserOrder();
	}

	private void updateOrderAndFlow(OrderByGaiZaoDTO orderDTO, OrderVO orderVo) throws SQLException {
		updateOrderAndFlow(orderDTO,orderVo,null);
	}

    private void updateOrderAndFlow(OrderByGaiZaoDTO orderDTO, OrderVO orderVo,FpOrderCostDTO fpOrderCost) throws SQLException {
		// 更新订单状态
		int result = orderDaoImpl.updateOrderByGaiZao(orderDTO);

		//状态更新成功
		if(result == 1){
			//记录订单流水
			OrderFlowDTO orderFlowDTO = new OrderFlowDTO();
			orderFlowDTO.setFlowDate(new Date());
			orderFlowDTO.setoStatus(orderDTO.getoStatus());
			orderFlowDTO.setoBackStatus(orderDTO.getoBackStatus());
			orderFlowDTO.setCreateBy(orderDTO.getUpdateBy());
			orderFlowDTO.setCreateDate(new Date());
			orderFlowDTO.setUpdateBy(orderDTO.getUpdateBy());
			orderFlowDTO.setUpdateDate(new Date());
			orderFlowDTO.setOrderId(orderDTO.getId());
			if(fpOrderCost != null) {
				orderFlowDTO.setRemark(fpOrderCost.getCostType());
			}
			orderDaoImpl.addOrderFlow(orderFlowDTO);

			//发送消息通知
			orderDTO.setoFAId(orderVo.getoFAId());
			orderDTO.setoProjectId(orderVo.getoProjectId());
			orderDTO.setoCId(orderVo.getoCId());

			try{
				// 将最新状态 赋值
				orderVo.setoStatus(orderDTO.getoStatus());
				sendMessage(orderVo);
			}catch(Exception e){
				log.error("send message error!",e);
			}

		}
	}

    @Override
	public BigDecimal getAllAmount(OrderDTO orderDTO) throws SQLException {
		
		return orderDaoImpl.getAllAmount(orderDTO);
	}

	@Override
	public List<Map<String, Object>> queryOrderOwnerUserCountAmount()
			throws SQLException {
		return orderDaoImpl.queryOrderOwnerUserCountAmount();
	}

}